﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QuanLyTruongHoc_App.MyDataSet.QLTHTableAdapters;

namespace QuanLyTruongHoc_App
{
    public partial class QHGVChuNhiem : Form
    {
        private int state;
        private Boolean wasSave, needReloadGV;
        private DataTable gvData;
        private MyDataSet.QLTH.tbl_KhoiDataTable tblKhoi;

        public QHGVChuNhiem()
        {
            InitializeComponent();

            LopHocMemu mn = new LopHocMemu(dg_DanhSach);
        }

        private void QLHinhThucCanBo_Load(object sender, EventArgs e)
        {
            loadCombo();
            refreshData();
        }

        private void checkUserPower()
        {
            int pow = PublicLib.getUserPower(PConst.QUYEN_QL_LOP_HOC);
            // user co quyen view
            tscb_NamHoc.Enabled = ((pow & PConst.POW_VIEW) > 0); // View cac nam hoc cu
            // user co quyen them
            tsb_TaoMoi.Enabled = ((pow & PConst.POW_ADD) > 0);
            // user co quyen edit
            tsb_Save.Enabled = 
                tsb_Edit.Enabled = ((pow & PConst.POW_EDIT) > 0);
            grc_GVChuNhiem.ReadOnly = !((pow & PConst.POW_EDIT) > 0);

            // user co delete
            tsb_Delete.Enabled = ((pow & PConst.POW_DEL) > 0);
        }

        private void loadCombo()
        {
            tbl_KhoiTableAdapter.Connection.ConnectionString = tbl_PhongHocTableAdapter.Connection.ConnectionString =
                tbl_CaHocTableAdapter.Connection.ConnectionString = tbl_KieuLopTableAdapter.Connection.ConnectionString =
                    tbl_LopHocTableAdapter.Connection.ConnectionString = PublicLib.getStrConn();

            this.tbl_KhoiTableAdapter.Fill(this.qLTH.tbl_Khoi);
            this.tbl_PhongHocTableAdapter.Fill(this.qLTH.tbl_PhongHoc);
            this.tbl_CaHocTableAdapter.Fill(this.qLTH.tbl_CaHoc);
            this.tbl_KieuLopTableAdapter.Fill(this.qLTH.tbl_KieuLop);
            this.tbl_LopHocTableAdapter.FillByFlag(this.qLTH.tbl_LopHoc, PConst.FLAG_NONE);
            // TODO: This line of code loads data into the 'qLTH.tbl_LopHoc' table. You can move, or remove it, as needed.
            //this.tbl_LopHocTableAdapter.Fill(this.qLTH.tbl_LopHoc);
            MyDataSet.QLTH.tbl_LopHocDataTable lopKeTiep = new QuanLyTruongHoc_App.MyDataSet.QLTH.tbl_LopHocDataTable();
            tbl_LopHocTableAdapter.FillByFlag(lopKeTiep, PConst.FLAG_NONE);
            DataRow r = lopKeTiep.NewRow();
            r[lopKeTiep.idColumn] = -1;
            r[lopKeTiep.TenLopColumn] = MSG.MNU_TOT_NGHIEP;
            r[lopKeTiep.flagColumn] = PConst.FLAG_NONE;
            lopKeTiep.Rows.Add(r);
            tblLopHocBindingSource1.DataSource = lopKeTiep;

            #region Nam Hoc
            // Nam Hoc
            MyDataSet.QLTHTableAdapters.tbl_NamHocTableAdapter namAdap = new MyDataSet.QLTHTableAdapters.tbl_NamHocTableAdapter();
            namAdap.Connection.ConnectionString = PublicLib.getStrConn();
            namAdap.FillByFlag(qLTH.tbl_NamHoc, PConst.FLAG_NONE);

            tscb_NamHoc.Items.Clear();
            for (int i = 0; i < qLTH.tbl_NamHoc.Rows.Count; i++)
            {
                tscb_NamHoc.Items.Add(qLTH.tbl_NamHoc.Rows[i][qLTH.tbl_NamHoc.TenColumn].ToString());
            }

            if (tscb_NamHoc.Items.Count > 0)
                tscb_NamHoc.SelectedIndex = tscb_NamHoc.Items.Count - 1;
            // -----------------
            #endregion
            #region Giao Vien
            // load Giao Vien
            gvData = new DataTable();
            gvData.Columns.Add("id", Type.GetType("System.Int32"));
            gvData.Columns.Add("ten", Type.GetType("System.String"));

            view_GiaoVienTableAdapter gvAdap = new view_GiaoVienTableAdapter();
            gvAdap.Connection.ConnectionString = PublicLib.getStrConn();

            if (tscb_NamHoc.SelectedIndex == tscb_NamHoc.Items.Count - 1)
            {
                gvAdap.FillByFlag(qLTH.view_GiaoVien, PConst.FLAG_NONE);
            }
            else
            {
                gvAdap.Fill(qLTH.view_GiaoVien);
            }

            for (int i = 0; i < qLTH.view_GiaoVien.Rows.Count; i++)
            {
                gvData.Rows.Add(qLTH.view_GiaoVien.Rows[i][qLTH.view_GiaoVien.idColumn],
                                qLTH.view_GiaoVien.Rows[i][qLTH.view_GiaoVien.HoDemColumn].ToString() + " " +
                                qLTH.view_GiaoVien.Rows[i][qLTH.view_GiaoVien.TenColumn].ToString() + " (" +
                                PublicLib.formatGVId((int)qLTH.view_GiaoVien.Rows[i][qLTH.view_GiaoVien.idColumn]) + ")");
            }
            grc_GVChuNhiem.SortMode = DataGridViewColumnSortMode.Automatic;
            grc_GVChuNhiem.DataSource = gvData;
            grc_GVChuNhiem.DisplayMember = "ten";
            grc_GVChuNhiem.ValueMember = "id";
            // --------------------
            #endregion
            #region Khoi lop
            tblKhoi = new QuanLyTruongHoc_App.MyDataSet.QLTH.tbl_KhoiDataTable();
            tbl_KhoiTableAdapter.FillByFlag(tblKhoi, PConst.FLAG_NONE);
            tscb_Khoi.Items.Clear();
            tscb_Khoi.Items.Add(MSG.MNU_ALL);
            for (int i = 0; i < tblKhoi.Rows.Count; i++)
            {
                tscb_Khoi.Items.Add(tblKhoi[i][tblKhoi.TenKhoiColumn]);
            }
            tscb_Khoi.SelectedIndex = 0;
            #endregion
        }

        private void refreshData()
        {
            state = PConst.STATE_LOAD;
            if (tscb_Khoi.SelectedIndex == 0)
            {
                // all
                tbl_LopHocTableAdapter.FillByFlag(this.qLTH.tbl_LopHoc, PConst.FLAG_NONE);
            }
            else
            {
                int idKhoi = (int)tblKhoi[tscb_Khoi.SelectedIndex - 1][tblKhoi.idColumn];
                tbl_LopHocTableAdapter.FillByKhoi(this.qLTH.tbl_LopHoc,idKhoi, PConst.FLAG_NONE);
            }
            
            needReloadGV = true;
            fillGiaoVien();

            state = PConst.STATE_LOADED;
        }

        private void fillGiaoVien()
        {
            int idNamHoc = (int)qLTH.tbl_NamHoc.Rows[tscb_NamHoc.SelectedIndex][qLTH.tbl_NamHoc.idColumn];

            if (needReloadGV)
            {
                MyDataSet.QLTHTableAdapters.qh_GVChuNhiemTableAdapter cnAdap = new qh_GVChuNhiemTableAdapter();
                cnAdap.Connection.ConnectionString = PublicLib.getStrConn();
                cnAdap.FillByNamHoc(qLTH.qh_GVChuNhiem, idNamHoc);
                needReloadGV = false;
            }

            for (int i = 0; i < dg_DanhSach.RowCount; i++)
            {
                dg_DanhSach[grc_STT.Index, i].Value = (i + 1);
                // Giao Vien Chu Nhiem
                int idLop = (int)(dg_DanhSach.Rows[i].Cells[grc_id.Index].Value);
                DataRow[] tmpRow = qLTH.qh_GVChuNhiem.Select(qLTH.qh_GVChuNhiem.idLopHocColumn.ColumnName +
                                                             "=" + idLop);
                if (tmpRow.Length == 0 || tmpRow[0][qLTH.qh_GVChuNhiem.idGiaoVienColumn] == DBNull.Value)
                    dg_DanhSach[grc_GVChuNhiem.Index, i].Value = DBNull.Value;
                else
                {
                    int idGV = (int)tmpRow[0][qLTH.qh_GVChuNhiem.idGiaoVienColumn];
                    DataRow[] sRow = gvData.Select("id=" + idGV);
                    if (sRow.Length > 0)
                    {
                        dg_DanhSach[grc_GVChuNhiem.Index, i].Value = sRow[0]["id"];
                    }
                }

                dg_DanhSach.Rows[i].DefaultCellStyle.BackColor = 
                    (i % 2 == 1) ? PConst.COLOR_BACK_1 : PConst.COLOR_BACK_DEF;
            }
            wasSave = true;
        }

        private void tsb_TaoMoi_Click(object sender, EventArgs e)
        {
            AddEditLopHoc frm_AddLop = new AddEditLopHoc();
            frm_AddLop.MdiParent = this.MdiParent;
            frm_AddLop.Show();
            frm_AddLop.Disposed += new EventHandler(frm_AddLop_Disposed);
        }

        private void bt_Sua_Click(object sender, EventArgs e)
        {
            if (dg_DanhSach.SelectedRows.Count == 0)
                return;
            //dg_DanhSach.SelectedRows[0].Cells[grc_GVChuNhiem.Index].Selected = true;
            //dg_DanhSach.BeginEdit(true);

            int i = int.Parse(dg_DanhSach.SelectedRows[0].Cells[grc_id.Name].Value.ToString());
            AddEditLopHoc frm_EditMH = new AddEditLopHoc();
            frm_EditMH.MdiParent = this.MdiParent;
            frm_EditMH.Show();
            frm_EditMH.setEditInfo(i);
            frm_EditMH.Disposed += new EventHandler(frm_AddLop_Disposed);
        }

        private void frm_AddLop_Disposed(object sender, EventArgs e)
        {
            try
            {
                refreshData();
                fillGiaoVien();
            }
            catch { }
        }

        private void bt_Xoa_Click(object sender, EventArgs e)
        {
            if (dg_DanhSach.SelectedRows.Count <= 0)
                return;
            if (MessageBox.Show(MSG.MSG_DELETE, "", MessageBoxButtons.YesNoCancel) == DialogResult.Yes)
            {
                deleteByID(dg_DanhSach.SelectedRows[0].Cells[grc_id.Name].Value.ToString());
            }
        }

        private void deleteByID(String _id)
        {
        
            try
            {
                DataRow[] r = qLTH.tbl_LopHoc.Select(qLTH.tbl_LopHoc.idColumn.ColumnName + "=" + _id);
                if (r.Length > 0)
                    r[0][qLTH.tbl_LopHoc.flagColumn] = PConst.FLAG_DELETE;
                tbl_LopHocTableAdapter.Update(qLTH.tbl_LopHoc);
                refreshData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(MSG.MSG_ERROR_INSERT_DB + " " + ex.Message);
            }
        }

        private void QLLoaiDiem_Resize(object sender, EventArgs e)
        {
            dg_DanhSach.Width = this.Width - 15;
            dg_DanhSach.Height = stts_Bottom.Top - dg_DanhSach.Top - 1;
        }

        private void dg_DanhSach_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (tsb_Edit.Enabled)
                bt_Sua_Click(tsb_Edit, new EventArgs());
        }

        private void saveData()
        {
            if (tscb_NamHoc.SelectedIndex == -1)
                return;
            int idNamHoc = (int)qLTH.tbl_NamHoc.Rows[tscb_NamHoc.SelectedIndex][qLTH.tbl_NamHoc.idColumn];
            
            MyDataSet.QLTHTableAdapters.qh_GVChuNhiemTableAdapter cnAdap = new qh_GVChuNhiemTableAdapter();
            cnAdap.Connection.ConnectionString = PublicLib.getStrConn();

            cnAdap.FillByNamHoc(qLTH.qh_GVChuNhiem, idNamHoc);
            
            for (int i = 0; i < dg_DanhSach.RowCount; i++)
            {
                // Save giao vien
                int idLop = (int)(dg_DanhSach.Rows[i].Cells[grc_id.Index].Value);
                DataRow[] tmpRow = qLTH.qh_GVChuNhiem.Select(qLTH.qh_GVChuNhiem.idLopHocColumn.ColumnName +
                                                             "=" + idLop);
                if (dg_DanhSach[grc_GVChuNhiem.Index, i].Value == DBNull.Value)
                {
                    if (tmpRow.Length > 0)
                    {
                        tmpRow[0].Delete();
                    }
                }
                else
                {
                    if (tmpRow.Length > 0)
                    {
                        tmpRow[0][qLTH.qh_GVChuNhiem.idGiaoVienColumn] = dg_DanhSach[grc_GVChuNhiem.Index, i].Value;
                    }
                    else
                    {
                        DataRow nRow = qLTH.qh_GVChuNhiem.NewRow();
                        nRow[qLTH.qh_GVChuNhiem.idNamHocColumn] = idNamHoc;
                        nRow[qLTH.qh_GVChuNhiem.idLopHocColumn] = idLop;
                        nRow[qLTH.qh_GVChuNhiem.idGiaoVienColumn] = dg_DanhSach[grc_GVChuNhiem.Index, i].Value;
                        qLTH.qh_GVChuNhiem.Rows.Add(nRow);
                    }
                }
                // -------------------
            }

            cnAdap.Update(qLTH.qh_GVChuNhiem);
            wasSave = true;
        }

        private void tsb_Save_Click(object sender, EventArgs e)
        {
            dg_DanhSach.EndEdit();
            saveData();
        }

        private void tscb_Lop_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (state == PConst.STATE_LOAD)
                return;
            if (!wasSave)
                if (MessageBox.Show(MSG.MSG_SAVE, "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    saveData();
            needReloadGV = true;
            fillGiaoVien();
        }

        private void dg_DanhSach_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            wasSave = false;
        }

        private void tsb_Reset_Click(object sender, EventArgs e)
        {
            loadCombo();
            refreshData();
        }

        private void dg_DanhSach_Sorted(object sender, EventArgs e)
        {
            fillGiaoVien();
        }

        private void QHGVChuNhiem_Shown(object sender, EventArgs e)
        {
            fillGiaoVien();
        }

        private void QHGVChuNhiem_FormClosing(object sender, FormClosingEventArgs e)
        {
            //for (int i=0; i< this.Form
            if (!wasSave)
                if (MessageBox.Show(MSG.MSG_SAVE, "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    saveData();
        }

        private void QHGVChuNhiem_Activated(object sender, EventArgs e)
        {
            checkUserPower();
        }

        private void tsb_In_Click(object sender, EventArgs e)
        {
            PrintDataGrid.PrintDGV print = new PrintDataGrid.PrintDGV();
            print.Print_DataGridView(dg_DanhSach);
        }

        private void tscb_Khoi_SelectedIndexChanged(object sender, EventArgs e)
        {
            refreshData();
        }

        private void dg_DanhSach_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            dg_DanhSach.Rows[e.RowIndex].Selected = true;
        }
    }
}
